<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="title" @ok="handleSubmit" :width="1000" :min-height="500">
    <BasicForm @register="registerForm" class="main-form" />
    <!-- 子列表区域 -->
    <div class="main-table">
      <a-tabs defaultActiveKey="1">
        <a-tab-pane tab="询价明细" key="1">
          <vxe-toolbar>
            <template #buttons>
              <a-button type="primary" @click="insertEvent()" class="toolbar-button"> 新增 </a-button>
              <a-button type="danger" @click="removeSelectedRows" class="toolbar-button"> 删除选中 </a-button>
            </template>
          </vxe-toolbar>

          <vxe-table
            border
            show-overflow
            keep-source
            ref="xTable"
            max-height="400"
            :data="rfqDetailList"
            :edit-config="{ trigger: 'click', mode: 'row', icon: 'fa fa-pencil', showStatus: true }"
          >
            <vxe-column type="checkbox" width="60" align="center" />
            <vxe-column type="seq" width="60" align="center" />
            <vxe-column field="goodsPic" title="产品图片" width="120">
              <template #default="{ row }">
                <img v-if="row.goodsPic" :src="row.goodsPic" class="product-image" />
                <span v-else>无图片</span>
              </template>
            </vxe-column>
            <vxe-column field="goodsName" title="产品中文名称" :edit-render="{ name: 'input', defaultValue: '' }" />
            <vxe-column field="goodsCode" title="产品编码" sortable :edit-render="{ name: 'input', defaultValue: '' }" />
            <vxe-column field="goodsSkuCode" title="产品sku编码" sortable :edit-render="{ name: 'input', defaultValue: '' }" />
            <vxe-column field="goodsModel" title="产品型号" :edit-render="{ name: 'input', defaultValue: '' }" />
            <vxe-column field="cgnum" title="产品采购数量" :edit-render="{ name: 'input', defaultValue: '' }" />
            <vxe-column field="mainlandQuotation" title="大陆报价" :edit-render="{ name: 'input', attrs: { type: 'number', step: 0.01 } }" />
            <vxe-column field="hkQuotation" title="香港报价" :edit-render="{ name: 'input', attrs: { type: 'number', step: 0.01 } }" />
          </vxe-table>
        </a-tab-pane>
      </a-tabs>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { VxeTableInstance } from 'vxe-table';
  import { formSchema } from '../RfqManage.data';
  import { saveOrUpdate, listqueryById } from '../RfqManage.api';

  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref(true);
  const currentRecord = ref<any>(null);
  const currentRfqId = ref<string | number | null>(null);
  const xTable = ref({} as VxeTableInstance);

  // 子表数据
  const rfqDetailList = ref<any[]>([]);

  //表单配置
  const [registerForm, { resetFields, setFieldsValue, validate, getFieldsValue }] = useForm({
    labelWidth: 150,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    setModalProps({
      confirmLoading: false,
      showCancelBtn: data?.showFooter,
      showOkBtn: data?.showFooter,
      defaultFullscreen: true,
    });
    isUpdate.value = !!data?.isUpdate;
    currentRecord.value = data?.record || null;

    if (unref(isUpdate)) {
      //编辑模式 - 通过listOne接口获取详情数据
      if (data.record.id) {
        try {
          setModalProps({ confirmLoading: true });
          const res = await listqueryById({ id: data.record.id });
          console.log('详情数据:', res);
          const detailData = res;

          // 设置主表字段值
          await setFieldsValue({
            ...detailData,
          });

          // 设置明细表数据
          // if (detailData.rfqManageDetailList) {
          //   rfqDetailList.value = detailData.rfqManageDetailList;
          // }

          currentRfqId.value = detailData?.id;
        } catch (error) {
          console.error('获取详情数据失败:', error);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }
    } else {
      //新增模式 - 先生成编码
      const rfqCode = generateRfqCode();
      await setFieldsValue({ rfqCode });
      currentRfqId.value = null;
      rfqDetailList.value = [];
    }
  });

  //设置标题
  const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

  //动态添加行
  async function insertEvent() {
    const $table = xTable.value;
    // 创建新行
    const record: any = {
      goodsName: '',
      goodsCode: '',
      goodsSkuCode: '',
      goodsModel: '',
      cgnum: 0,
      mainlandQuotation: 0,
      hkQuotation: 0,
    };

    const { row: newRow } = await $table.insertAt(record, -1);
    await $table.setActiveCell(newRow, 'goodsName');
  }

  //删除选中行
  async function removeSelectedRows() {
    const $table = xTable.value;
    const selectRecords = $table.getCheckboxRecords();
    if (selectRecords.length === 0) {
      return;
    }
    await $table.removeCheckboxRow();
  }

  //表单提交事件
  async function handleSubmit(v) {
    try {
      let values = await validate();
      setModalProps({ confirmLoading: true });

      // 获取子表数据
      const $table = xTable.value;
      const { fullData } = $table.getTableData();

      // 过滤掉完全空的行
      const validDetailData = fullData.filter((item) => item.goodsName || item.goodsCode || item.goodsSkuCode || item.goodsModel || item.cgnum);

      // 组装提交数据，用rfqManage包裹主表数据
      const submitData = {
        rfqManage: {
          ...values,
        },
        rfqManageDetailList: validDetailData,
      };

      // 提交完整数据（主表+明细）
      const result = await saveOrUpdate(submitData, unref(isUpdate));

      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success', {
        isUpdate: isUpdate.value,
        values: {
          ...submitData,
          id: result.data?.id || result.id,
        },
      });
    } catch (error) {
      console.error('保存失败:', error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  function generateRfqCode() {
    // 调用后端接口或使用shop_order_num规则生成编码
    // 示例格式：RFQ202312010001
    const date = new Date();
    const dateString = date.toISOString().slice(0, 10).replace(/-/g, '');
    const randomNum = Math.floor(Math.random() * 10000)
      .toString()
      .padStart(4, '0');
    return `RFQ${dateString}${randomNum}`;
  }
</script>

<style lang="less" scoped>
  .main-form {
    margin-top: 20px;
  }

  .main-table {
    padding: 20px;

    .toolbar-button {
      margin-right: 10px;
    }

    .product-image {
      width: 60px;
      height: 60px;
      object-fit: cover;
    }
  }

  :deep(.ant-form-item) {
    margin-bottom: 12px;
  }
</style>
